package com.example.pceb.service.Impl;

import cn.hutool.core.lang.mutable.MutableFloat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pceb.VO.LoginVO;
import com.example.pceb.entity.*;
import com.example.pceb.mapper.*;
import com.example.pceb.result.Result;
import com.example.pceb.result.ResultCode;
import com.example.pceb.service.UserService;
import com.example.pceb.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.Claims;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import java.util.Date;
import java.util.List;
import static com.example.pceb.result.Result.fail;
import static com.example.pceb.result.Result.success;
import com.example.pceb.utils.OperationLogUtils;
import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private SchoolAdminMapper schoolAdminMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private MentorMapper mentorMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Override
    public Result<List<User>> selectAllUser() {
        List<User> userList = userMapper.selectList(null);
        return success(userList, ResultCode.OK);
    }

    @Override
    public Result<Object> getUserInfo(String token) {
        if (token == null || !token.startsWith("Bearer ")) {
            return fail("Token无效或格式不正确", ResultCode.FAIL);
        }
        token = token.substring(7); // Remove "Bearer " prefix

        try {
            Claims claims = JwtUtil.parseToken(token);
            String username = claims.get("username", String.class);
            String identity = claims.get("identity", String.class);

            switch (identity) {
                case "0": // 管理员
                    QueryWrapper<Admin> adminQuery = new QueryWrapper<>();
                    adminQuery.eq("username", username);
                    Admin admin = adminMapper.selectOne(adminQuery);
                    return success(admin);
                case "1": // 学校管理员
                    QueryWrapper<SchoolAdmin> schoolAdminQuery = new QueryWrapper<>();
                    schoolAdminQuery.eq("username", username);
                    SchoolAdmin schoolAdmin = schoolAdminMapper.selectOne(schoolAdminQuery);
                    return success(schoolAdmin);
                case "2": // 企业
                    QueryWrapper<Enterprise> enterpriseQuery = new QueryWrapper<>();
                    enterpriseQuery.eq("username", username);
                    Enterprise enterprise = enterpriseMapper.selectOne(enterpriseQuery);
                    return success(enterprise);
                case "3": // 教师
                    QueryWrapper<Teacher> teacherQuery = new QueryWrapper<>();
                    teacherQuery.eq("username", username);
                    Teacher teacher = teacherMapper.selectOne(teacherQuery);
                    return success(teacher);
                case "4": // 学生
                    QueryWrapper<Student> studentQuery = new QueryWrapper<>();
                    studentQuery.eq("username", username);
                    Student student = studentMapper.selectOne(studentQuery);
                    return success(student);
                case "5": // 企业导师
                    QueryWrapper<Mentor> mentorQuery = new QueryWrapper<>();
                    mentorQuery.eq("username", username);
                    Mentor mentor = mentorMapper.selectOne(mentorQuery);
                    return success(mentor);
                default:
                    return fail("无效的用户身份！", ResultCode.FAIL);
            }
        } catch (Exception e) {
            return fail("Token无效或已过期", ResultCode.FAIL);
        }
    }

    @Override
    public Result<String> loginByUserName(String username, String password, String identity) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null || !password.equals(user.getPassword()) || !identity.equals(user.getIdentity())) {
            return fail("用户名、密码或身份不正确！", ResultCode.FAIL);
        }

        String token = JwtUtil.generateToken(username, identity);
        // 记录登录操作日志
        OperationLogUtils.saveOperationLog(
            null, // 无id字段
            username,
            "登录",
            "用户登录",
            null, // 无法获取request对象
            "loginByUserName",
            "username=" + username + ",identity=" + identity,
            "登录成功"
        );
        return success(token);
    }

    @Override
    public Result<String> loginByToken(String token) {
        try {
            Claims claims = JwtUtil.parseToken(token);
            String username = claims.get("username", String.class);
            String identity = claims.get("identity", String.class);

            // 返回包含用户名和身份的JSON字符串
            String result = "{\"username\":\"" + username + "\",\"identity\":\"" + identity + "\"}";
            return success(result);
        } catch (Exception e) {
            return fail("Token无效或已过期", ResultCode.FAIL);
        }
    }

    @Override
    public Result<String> register(LoginVO loginVO) {
        try {
            // 检查用户是否已存在
            QueryWrapper<User> userQuery = new QueryWrapper<>();
            userQuery.eq("username", loginVO.getUsername());
            if (userMapper.selectOne(userQuery) != null) {
                return fail("用户名已存在！", ResultCode.FAIL);
            }

            // 对于需要审核的身份，直接返回提示
            if ("0".equals(loginVO.getIdentity()) || "1".equals(loginVO.getIdentity()) || "2".equals(loginVO.getIdentity())) {
                return fail("管理员身份需要审核，请通过审核申请流程注册", ResultCode.FAIL);
            }

            User user = new User();
            user.setUsername(loginVO.getUsername());
            user.setPassword(loginVO.getPassword());
            user.setIdentity(loginVO.getIdentity());
            user.setPhone("");
            user.setEmail("");

            int userInsert = userMapper.insert(user);
            if (userInsert != 1) {
                return fail("User表插入失败", ResultCode.FAIL);
            }

            switch (loginVO.getIdentity()) {
                case "3": // 教师
                    Teacher teacher = new Teacher();
                    teacher.setUsername(loginVO.getUsername());
                    teacher.setName(loginVO.getUsername());
                    teacher.setSchoolId(10);
                    teacher.setPhone("");
                    teacher.setEmail("");
                    teacherMapper.insert(teacher);
                    break;
                case "4": // 学生
                    Student student = new Student();
                    student.setUsername(loginVO.getUsername());
                    student.setName(loginVO.getUsername());
                    student.setPhone("");
                    student.setEmail("");
                    student.setSchool("中南大学");
                    student.setSchoool_time(new java.sql.Date(System.currentTimeMillis()));
                    studentMapper.insert(student);
                    break;
                case "5": // 企业导师
                    Mentor mentor = new Mentor();
                    mentor.setUsername(loginVO.getUsername());
                    mentor.setName(loginVO.getUsername());
                    mentor.setEnterpriseId("1939284610046906370");
                    mentor.setPhone("");
                    mentor.setEmail("");
                    mentorMapper.insert(mentor);
                    break;
                default:
                    return fail("无效的用户身份！", ResultCode.FAIL);
            }

            return success("注册成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return fail("注册异常: " + e.getMessage(), ResultCode.FAIL);
        }
    }

    /**
     * 更新用户信息
     * @param token 用户的Token
     * @param userData 用户数据
     * @return Result
     */
    @Override
    public Result<Object> updateUserInfo(String token, Object userData) {
        if (token == null || !token.startsWith("Bearer ")) {
            return fail("Token无效或格式不正确", ResultCode.FAIL);
        }
        token = token.substring(7);

        try {
            Claims claims = JwtUtil.parseToken(token);
            String username = claims.get("username", String.class);
            String identity = claims.get("identity", String.class);
            System.out.println("收到的用户身份 (identity): " + identity);

            int updatedRows = 0;
            ObjectMapper objectMapper = new ObjectMapper();

            switch (identity) {
                case "0": // 管理员
                    Admin adminData = objectMapper.convertValue(userData, Admin.class);
                    if (!username.equals(adminData.getUsername())) return fail("无权修改其他用户信息", ResultCode.FAIL);
                    updatedRows = adminMapper.updateById(adminData);
                    break;
                case "1": // 学校管理员
                    SchoolAdmin schoolAdminData = objectMapper.convertValue(userData, SchoolAdmin.class);
                    if (!username.equals(schoolAdminData.getUsername())) return fail("无权修改其他用户信息", ResultCode.FAIL);
                    updatedRows = schoolAdminMapper.updateById(schoolAdminData);
                    break;
                case "2": // 企业
                    Enterprise enterpriseData = objectMapper.convertValue(userData, Enterprise.class);
                    if (!username.equals(enterpriseData.getUsername())) return fail("无权修改其他用户信息", ResultCode.FAIL);
                    updatedRows = enterpriseMapper.updateById(enterpriseData);
                    break;
                case "3": // 教师
                    Teacher teacherData = objectMapper.convertValue(userData, Teacher.class);
                    if (!username.equals(teacherData.getUsername())) return fail("无权修改其他用户信息", ResultCode.FAIL);
                    // 新增：校验schoolId是否存在
                    Integer newSchoolId = teacherData.getSchoolId();
                    if (newSchoolId != null) {
                        School school = schoolMapper.selectById(newSchoolId);
                        if (school == null) {
                            return fail("学校ID不存在，无法更新！", ResultCode.FAIL);
                        }
                    }
                    updatedRows = teacherMapper.updateById(teacherData);
                    break;
                case "4": // 学生
                    Student studentData = objectMapper.convertValue(userData, Student.class);
                    if (!username.equals(studentData.getUsername())) return fail("无权修改其他用户信息", ResultCode.FAIL);
                    updatedRows = studentMapper.updateById(studentData);
                    break;
                case "5": // 企业导师
                    Mentor mentorData = objectMapper.convertValue(userData, Mentor.class);
                    if (!username.equals(mentorData.getUsername())) return fail("无权修改其他用户信息", ResultCode.FAIL);
                    // 校验 enterprise_id 是否存在
                    String newEnterpriseId = mentorData.getEnterpriseId();
                    if (newEnterpriseId != null && !newEnterpriseId.isEmpty()) {
                        QueryWrapper<Enterprise> enterpriseQuery = new QueryWrapper<>();
                        enterpriseQuery.eq("id", newEnterpriseId);
                        Enterprise enterprise = enterpriseMapper.selectOne(enterpriseQuery);
                        if (enterprise == null) {
                            return fail("企业ID不存在", ResultCode.FAIL);
                        }
                    }
                    updatedRows = mentorMapper.updateById(mentorData);
                    break;
                default:
                    return fail("该用户身份不支持信息修改", ResultCode.FAIL);
            }

            if (updatedRows > 0) {
                // 记录信息修改操作日志
                OperationLogUtils.saveOperationLog(
                    null, // 无id字段
                    username,
                    "信息修改",
                    "用户信息修改",
                    null, // 无法获取request对象
                    "updateUserInfo",
                    userData.toString(),
                    "信息修改成功"
                );
                return success("用户信息更新成功");
            } else {
                return fail("用户信息更新失败", ResultCode.FAIL);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return fail("Token无效或更新过程中发生错误: " + e.getMessage(), ResultCode.FAIL);
        }
    }

    @Override
    public Result<String> uploadAvatar(String token, String identity, String username, MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return Result.fail("文件不能为空", ResultCode.FAIL);
        }
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        // 保存路径
        String uploadDir = "D:/成都实训项目/school-enterprise-alliance/src/main/resources/uploads/avatar/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();
        File dest = new File(uploadDir + fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return Result.fail("文件保存失败", ResultCode.FAIL);
        }
        // 数据库存相对路径
        String avatarUrl = "/uploads/avatar/" + fileName;
        // 根据身份更新不同表
        if ("0".equals(identity)) { // 管理员
            QueryWrapper<Admin> query = new QueryWrapper<>();
            query.eq("username", username);
            Admin admin = adminMapper.selectOne(query);
            if (admin != null) {
                admin.setAvatarUrl(avatarUrl);
                adminMapper.updateById(admin);
            }
        } else if ("4".equals(identity)) { // 学生
            QueryWrapper<Student> query = new QueryWrapper<>();
            query.eq("username", username);
            Student student = studentMapper.selectOne(query);
            if (student != null) {
                student.setAvatarUrl(avatarUrl);
                studentMapper.updateById(student);
            }
        } else if ("2".equals(identity)) { // 企业
            QueryWrapper<Enterprise> query = new QueryWrapper<>();
            query.eq("username", username);
            Enterprise enterprise = enterpriseMapper.selectOne(query);
            if (enterprise != null) {
                enterprise.setAvatarUrl(avatarUrl);
                enterpriseMapper.updateById(enterprise);
            }
        }
        return Result.success(avatarUrl);
    }

    @Override
    public int countAllUsers() {
        return userMapper.countAllUsers();
    }

    @Override
    public java.util.List<java.util.Map<String, Object>> countUserByIdentity() {
        return userMapper.countUserByIdentity();
    }
}